/**
 * 树形数据扁平化
 */
export function flatTree(tree, children = 'childMenus') {
  let arr = []
  tree.length &&
    tree.forEach((item) => {
      if (item[children] && item[children].length) {
        arr.push(...flatTree(item[children]))
        arr.push(item)
      } else {
        arr.push(item)
      }
    })
  return arr
}

/**
 * 根据当前元素的id,寻找最外层元素。如果元素的pid为1.则为最外层元素
 */
//
export function findOutermostParent(menu: any, tree: any, children = 'childMenus') {
  if (Number(menu.pid) !== 1) {
    let route = flatTree(tree, children).find((item) => item.id === menu.pid)
    if (route) {
      return findOutermostParent({ id: route.id, pid: route.menuPid }, tree, children)
    }
  } else {
    return menu
  }
}
